import { useState, useRef, useEffect } from 'react';
import { X, Plus } from 'lucide-react';
import { useDiaryStore } from '../store/diaryStore';

interface TagInputProps {
  tags: string[];
  onChange: (tags: string[]) => void;
  placeholder?: string;
}

const TAG_COLORS = [
  'bg-emerald-100 text-emerald-800 border-emerald-200',
  'bg-blue-100 text-blue-800 border-blue-200',
  'bg-purple-100 text-purple-800 border-purple-200',
  'bg-orange-100 text-orange-800 border-orange-200',
  'bg-pink-100 text-pink-800 border-pink-200',
  'bg-indigo-100 text-indigo-800 border-indigo-200',
  'bg-teal-100 text-teal-800 border-teal-200',
  'bg-amber-100 text-amber-800 border-amber-200',
];

const getTagColor = (tag: string) => {
  const hash = tag.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  return TAG_COLORS[Math.abs(hash) % TAG_COLORS.length];
};

export const TagInput = ({ tags, onChange, placeholder = 'Add tags...' }: TagInputProps) => {
  const [inputValue, setInputValue] = useState('');
  const [showSuggestions, setShowSuggestions] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const { getAllTags, getPopularTags } = useDiaryStore();
  
  const allTags = getAllTags();
  const popularTags = getPopularTags(5);
  
  const suggestions = inputValue
    ? allTags.filter(tag => 
        tag.toLowerCase().includes(inputValue.toLowerCase()) &&
        !tags.includes(tag)
      )
    : popularTags.map(t => t.tag).filter(tag => !tags.includes(tag));

  const addTag = (tag: string) => {
    const trimmedTag = tag.trim();
    if (trimmedTag && !tags.includes(trimmedTag)) {
      onChange([...tags, trimmedTag]);
    }
    setInputValue('');
    setShowSuggestions(false);
  };

  const removeTag = (tagToRemove: string) => {
    onChange(tags.filter(tag => tag !== tagToRemove));
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      if (inputValue.trim()) {
        addTag(inputValue);
      }
    } else if (e.key === 'Backspace' && !inputValue && tags.length > 0) {
      removeTag(tags[tags.length - 1]);
    } else if (e.key === 'Escape') {
      setShowSuggestions(false);
    }
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (inputRef.current && !inputRef.current.contains(event.target as Node)) {
        setShowSuggestions(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <div className="relative">
      <div className="min-h-[42px] p-3 border border-sage/30 rounded-lg bg-white focus-within:border-forest focus-within:ring-2 focus-within:ring-forest/10">
        <div className="flex flex-wrap gap-2 items-center">
          {tags.map((tag) => (
            <span
              key={tag}
              className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium border ${
                getTagColor(tag)
              }`}
            >
              {tag}
              <button
                type="button"
                onClick={() => removeTag(tag)}
                className="hover:bg-black/10 rounded-full p-0.5 transition-colors"
              >
                <X className="w-3 h-3" />
              </button>
            </span>
          ))}
          <div className="flex-1 min-w-[120px]">
            <input
              ref={inputRef}
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyDown}
              onFocus={() => setShowSuggestions(true)}
              placeholder={tags.length === 0 ? placeholder : ''}
              className="w-full border-none outline-none bg-transparent text-sm placeholder-gray-400"
            />
          </div>
        </div>
      </div>
      
      {showSuggestions && suggestions.length > 0 && (
        <div className="absolute z-10 w-full mt-1 bg-white border border-sage/30 rounded-lg shadow-lg max-h-48 overflow-y-auto">
          {!inputValue && (
            <div className="px-3 py-2 text-xs font-medium text-gray-500 border-b border-sage/20">
              Popular tags
            </div>
          )}
          {suggestions.map((tag) => (
            <button
              key={tag}
              type="button"
              onClick={() => addTag(tag)}
              className="w-full px-3 py-2 text-left text-sm hover:bg-sage/10 transition-colors flex items-center gap-2"
            >
              <Plus className="w-3 h-3 text-gray-400" />
              <span className={`px-2 py-0.5 rounded-full text-xs font-medium border ${
                getTagColor(tag)
              }`}>
                {tag}
              </span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};